package com.just.springbootnosql;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.just.springbootnosql.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class Receiver {
    private static final Logger logger=LoggerFactory.getLogger(Receiver.class);
    private CountDownLatch latch;
    //我们给Receiver的构造函数通过@AutoWired标注注入了一个CountDownLatch实例，当接收到消息时，调用cutDown()方法。
    @Autowired
    public Receiver(CountDownLatch latch){
        this.latch=latch;
    }

    public void receiveMessage(String message){
        logger.info("receive message:"+message);
        latch.countDown();
    }

    public void receiveJsonMessage(String message){
        logger.info("receive json message:"+message);
        ObjectMapper mapper=new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        //GenericJackson2JsonRedisSerializer 里会有class的类路径，可以直接反序列化
        //GenericJackson2JsonRedisSerializer g=new GenericJackson2JsonRedisSerializer();
        try {
            User user=mapper.readValue(message,User.class);
            //User user=(User) g.deserialize(message.getBytes());
            logger.info("反序列化为user成功，userId:"+user.getId());
        } catch (Exception e) {
            logger.info("这不是user");
        }
        latch.countDown();
    }

}
